package com.leyou.auth.controller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author CHERRY
 * @date 2018-09-16-19:14
 */
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class);

    /**
     * 授权登录
     *
     * @param request
     * @param response
     * @param username
     * @param password
     * @return
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam("username") String username,
            @RequestParam("password") String password) {

        //登录验证
        String token = this.authService.authentication(username, password);

        if (StringUtils.isBlank(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        //token 保存到cookie
        CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token,
                jwtProperties.getCookieMaxAge(), "utf-8", true);

        return ResponseEntity.ok().build();
    }

    /**
     * 校验用户是否处于登录状态
     *
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(HttpServletResponse response, HttpServletRequest request,
                                               @CookieValue("LEYOU_TOKEN") String LEYOU_TOKEN) {
        try {
            //获取cookie
            //String LEYOU_TOKEN = CookieUtils.getCookieValue(request, "LEYOU_TOKEN", "utf-8");

            // 根据token获取用户信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(LEYOU_TOKEN, jwtProperties.getPublicKey());
            //解析成功，更新token cookie
            String token = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(),
                    jwtProperties.getExpire());

            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token,
                    jwtProperties.getCookieMaxAge());

            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            LOGGER.error("校验用户是否登录异常" + e);
        }

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }


}

